'use strict';
/**
 * Clip-Two Main Controller
 */
app.controller('AppCtrl', ['$rootScope', '$scope', '$state', '$translate', '$localStorage', '$cookieStore', '$window', '$modal', '$document', '$timeout', '$filter', '$auth', 'cfpLoadingBar', 'Restangular', 'api_login',
    function($rootScope, $scope, $state, $translate, $localStorage, $cookieStore, $window, $modal, $document, $timeout, $filter, $auth, cfpLoadingBar, Restangular, api_login) {

        // Loading bar transition
        // -----------------------------------

        var $win = $($window);
        // window.onbeforeunload = function() {
        //     // $auth.deleteData('auth_headers')
        //     $rootScope.logout();
        // }
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            //start loading bar on stateChangeStart
            cfpLoadingBar.start();
            // var myCache = $cacheFactory('myCache');
            if (!JSON.parse(sessionStorage.getItem('header'))) {
                if (toState.name != "login.signin" && (!$auth.userIsAuthenticated())) {
                    event.preventDefault();
                    $rootScope.app.isLoginFixed = true;
                    return $state.go("login.signin");
                }
                if ($auth.userIsAuthenticated()) {
                    $auth.validateUser();
                }
            } else {
                // console.log("toState.name="+ JSON.stringify(toState));
                if (isEmpty($auth.retrieveData('auth_headers'))) {
                    if (toState.name != "login.signin" && (!$auth.userIsAuthenticated())) {
                        event.preventDefault();
                        $rootScope.app.isLoginFixed = true;
                        return $state.go("login.signin");
                    }
                }
            }
            // $auth.validateUser();
        });


        window.onunload = function() {
            // getMenus();
            // $auth.invalidateTokens();
            // $auth.signOut()
            // .then(function(resp) {
            //     console.log(' resp1='+JSON.stringify( resp));
            //   // handle success response
            // })
            // .catch(function(resp) {
            //     console.log(' resp2='+JSON.stringify( resp));
            //      // $state.go('login.signin');
            //   // handle error response
            // });
            // $auth.invalidateTokens();
            // $timeout(function () {
            //      SweetAlert.swal({ title: "正在登出中...", type: "success"});
            // }, 1000);

        }
        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            //$auth.validateUser();
            //stop loading bar on stateChangeSuccess
            event.targetScope.$watch("$viewContentLoaded", function() {
                cfpLoadingBar.complete();
            });

            // scroll top the page on change state

            $document.scrollTo(0, 0);
            if (angular.element('.email-reader').length) {
                angular.element('.email-reader').animate({
                    scrollTop: 0
                }, 0);
            }

            // Save the route title
            $rootScope.currTitle = $state.current.title;
            if (angular.isDefined($state.current.pdKey)) {
                $rootScope.pdKey = $state.current.pdKey;
            }
            // console.log($state.current.title);
        });

        // State not found
        $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams) {
            //$rootScope.loading = false;
            if (angular.isUndefined($rootScope.user.id)) {
                $rootScope.loading = false;
            }
            console.log(unfoundState.to);
            // "lazy.state"
            console.log(unfoundState.toParams);
            // {a:1, b:2}
            console.log(unfoundState.options);
            // {inherit:false} + default options
        });

        $rootScope.$on('auth:login-success', function(ev, data) {
            getMenus();
            //console.log(data);
            //$rootScope.user = data.user;
            //$rootScope.menus = data.menu;   
        });

        // $rootScope.$watch('$auth.user', function(ev){

        // })

        $rootScope.$on('auth:validation-success', function(ev, user) {
            // console.log(user);
            if ($rootScope.userMenus.length == 0) {
                getMenus();
            }

            //alert('Welcome ', user.email);
        });

        $rootScope.$on('auth:invalid', function(ev) {
            $state.go('login.signin');
        });

        $rootScope.$on('auth:validation-error', function(ev) {
            $state.go('login.signin');
            //alert('Welcome ', user.email);
        });

        $rootScope.$on('auth:session-expired', function(ev) {
            //alert('Welcome ', user.email);
            $state.go('login.signin');
        });

        $rootScope.$on('auth:logout-success', function(ev) {
            //alert('goodbye');
            //delete $rootScope.user;
            //delete $rootScope.menus;  
            $state.go('login.signin');
        });

        $rootScope.$on('auth:logout-error', function(ev) {
            $state.go('login.signin');
        });



        $rootScope.pageTitle = function() {
            // if($rootScope.currTitle){
            //     return $rootScope.app.name + ' - ' + $filter('translate')($rootScope.currTitle) || $rootScope.app.description;
            // }else{
            //     return $rootScope.app.name + ' - ' + $rootScope.app.description
            // }
            var perfix = "sidebar.nav.";
            var toTransKeypageTitle = perfix + $rootScope.currTitle;
            return $rootScope.app.name + ' - ' + ($filter('translate')(toTransKeypageTitle) || $rootScope.app.description);
        };


        // $auth.validateUser();
        // $auth.authenticate('local').then(function(resp){

        // }).catch(function(resp){

        // })

        // if(angular.isDefined($rootScope.nickname)){
        //     api_login.sso($rootScope.nickname).then(function(response){
        //         var user = Restangular.stripRestangular(response);
        //         if (user) {
        //             if(angular.isUndefined(user.id)){

        //             }else{
        //                 $rootScope.user = user;                
        //             }
        //         }
        //     });
        // }else{
        // var user= $cookieStore.get("userObm");
        // if(user){
        //     $rootScope.user = user;
        //     $rootScope.menus = $cookieStore.get("menuObm");
        // }else{
        //     if(angular.isDefined($rootScope.nickname)){
        //         api_login.sso($rootScope.nickname).then(function(response){
        //             var data = Restangular.stripRestangular(response);
        //             if (data) {
        //                 if(data.user){
        //                     if(angular.isUndefined(data.user.id)){

        //                     }else{
        //                         $rootScope.user = data.user;
        //                         $rootScope.menus = data.menu;  
        //                         $cookieStore.put("userObm", $rootScope.user);
        //                         $cookieStore.put("menuObm", $rootScope.menus);
        //                         $cookieStore.put("session", data.sessionId);  
        //                     }
        //                 }
        //             }
        //         });
        //     }else{

        //     }
        // }
        //}

        $scope.includes = [];
        $rootScope.includesState = function(state) {
            //for test
            //return true;
            //return includes;
            if ($rootScope.user) {
                if ($rootScope.user.menu) {
                    angular.forEach($rootScope.user.menu, function(item) {
                        $scope.includes[item.link] = true;
                    });
                }
            }
            return $scope.includes[state];
        }
        $rootScope.changepassword = function(data1, size) {
            var modalInstance = $modal.open({
                templateUrl: 'assets/views/changepassword.html',
                controller: function($scope, $modalInstance, items, Restangular, SweetAlert) {
                    $scope.passwordnull = function(originalPwd, pwd, pwd_2) {
                        return originalPwd == undefined || pwd == undefined || pwd_2 == undefined || originalPwd == "" || pwd == "" || pwd_2 == "" || originalPwd == "null" || pwd == "null" || pwd_2 == "null";
                    }
                    $scope.savepassword = function(originalPwd, pwd, pwd_2) {
                        $modalInstance.dismiss('cancel');
                        console.log('pwd=' + pwd + '+' + pwd_2);
                        // if(angular.isDefined(pwd)&&angular.isDefined(pwd_2)){
                        if (pwd == pwd_2) {
                            var data2 = {};
                            data2["originalPwd"] = originalPwd;
                            data2["userid"] = $rootScope.user.uid;
                            data2["pwd"] = pwd;
                            api_login.uppwd(data2).then(function(response) {
                                var myData = Restangular.stripRestangular(response);
                                if (myData.status == 200) {
                                    SweetAlert.swal({
                                        title: "保存成功!",
                                        type: "success",
                                        confirmButtonColor: "#007AFF"
                                    });
                                } else {
                                    SweetAlert.swal({
                                        title: "保存失败!",
                                        text: "输入旧密码错误，请重新输入！",
                                        type: "error"
                                    });
                                }
                            })

                        } else {
                            SweetAlert.swal({
                                title: "两次输入的新密码不相同!",
                                text: "输入错误，请重新输入！",
                                type: "error"
                            });
                        }
                        // }else{
                        //     SweetAlert.swal({
                        //                     title: "密码不能为空!",
                        //                     text: "请输入密码！",
                        //                     type: "error"
                        //                 });
                        // }
                    }
                },
                size: size,
                resolve: {
                    items: function() {
                        return {
                            fetchItems: function(filterData, APIService) {}
                        };
                    },
                }
            });
        }
        $rootScope.userMenus = [];

        var getMenus = function() {
            function convertListToTree(data, treeMap) {
                var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
                var root = null; //Initially set our loop to null
                var parentNode = null;
                //loop over data
                for (var i = 0; i < data.length; i++) {
                    var datum = data[i];
                    //each node will have children, so let's give it a "children" poperty
                    datum.children = [];

                    //add an entry for this node to the map so that any future children can
                    //lookup the parent
                    idToNodeMap[datum.id] = datum;

                    //Does this node have a parent?
                    if (typeof datum.parentid === "undefined" || datum.parentid == null) {
                        //Doesn't look like it, so this node is the root of the tree
                        root = datum;
                        treeMap[datum.id] = root;
                    } else {
                        //This node has a parent, so let's look it up using the id
                        parentNode = idToNodeMap[datum.parentid];

                        //We don't need this property, so let's delete it.
                        //delete datum.parentid;

                        //Let's add the current node as a child of the parent node.
                        parentNode.children.push(datum);

                    }
                }
                return root;
            }

            function convertParentToChildList(data) {
                var treeMap = {};
                var list = [];
                convertListToTree(data, treeMap);
                angular.forEach(treeMap, function(item) {
                    list.push(item);
                });
                list = window._.sortBy(list, function(o) { return o.order; });
                return list;
            }

            //if(userMenus.length==0){
            var userMenus = [];
            var idMapMenu = {};
            if ($rootScope.user) {
                if ($rootScope.user.menu) {
                    userMenus = convertParentToChildList($rootScope.user.menu);
                }
            }
            //}
            $rootScope.userMenus = userMenus;
            return userMenus;
        }

        getMenus();

        // console.log("$rootScope.nickname="+JSON.stringify($rootScope));
        $rootScope.logout = function() {
            // var  userid =data.id;
            // console.log(' userid='+JSON.stringify( userid));
            $auth.signOut()
                .then(function(resp) {
                    $rootScope.search = {};
                    // $auth.deleteData('auth_headers')
                    sessionStorage.clear();
                    $state.go('login.signin');
                })
                .catch(function(resp) {
                    // console.log(' resp2='+JSON.stringify( resp));
                    // $state.go('login.signin');
                    // handle error response
                });
            //$cookieStore.remove("userObm");
            //$cookieStore.remove("menuObm");
            //$cookieStore.remove("session");
            //$rootScope.user = undefined;
            //$rootScope.menus = undefined;
            //$rootScope.nickname = undefined;
            //window.location = "http://www.itsm.com:8080/itsm/dev/logout.jsp";
            // //logout: function(noServerLogout){
            //     window.sessionStorage.clear();
            //     window.location = "https://www.yunwei.com:8443/cas/loginout";
            // //},
        }


        // save settings to local storage
        if (angular.isDefined($localStorage.layout)) {
            $scope.app.layout = $localStorage.layout;
        } else {
            $localStorage.layout = $scope.app.layout;
        }
        $scope.$watch('app.layout', function() {
            // save to local storage
            $localStorage.layout = $scope.app.layout;
        }, true);

        //global function to scroll page up
        $scope.toTheTop = function() {
            $document.scrollTopAnimated(0, 600);
        };

        // angular translate
        // ----------------------

        $scope.language = {
            // Handles language dropdown
            listIsOpen: false,
            // list of available languages
            available: {
                'en': 'English',
                'it_IT': 'Italiano',
                'de_DE': 'Deutsch',
                'zh_cn': 'Chinese'
            },
            // display always the current ui language
            init: function() {
                var proposedLanguage = $translate.proposedLanguage() || $translate.use();
                var preferredLanguage = $translate.preferredLanguage();
                // we know we have set a preferred one in app.config
                $scope.language.selected = $scope.language.available[(proposedLanguage || preferredLanguage)];
            },
            set: function(localeId, ev) {
                $translate.use(localeId);
                $scope.language.selected = $scope.language.available[localeId];
                $scope.language.listIsOpen = !$scope.language.listIsOpen;
            }
        };

        $scope.language.init();

        // Function that find the exact height and width of the viewport in a cross-browser way
        var viewport = function() {
            var e = window,
                a = 'inner';
            if (!('innerWidth' in window)) {
                a = 'client';
                e = document.documentElement || document.body;
            }
            return {
                width: e[a + 'Width'],
                height: e[a + 'Height']
            };
        };
        // function that adds information in a scope of the height and width of the page
        $scope.getWindowDimensions = function() {
            return {
                'h': viewport().height,
                'w': viewport().width
            };
        };
        // Detect when window is resized and set some variables
        $scope.$watch($scope.getWindowDimensions, function(newValue, oldValue) {
            $scope.windowHeight = newValue.h;
            $scope.windowWidth = newValue.w;
            if (newValue.w >= 992) {
                $scope.isLargeDevice = true;
            } else {
                $scope.isLargeDevice = false;
            }
            if (newValue.w < 992) {
                $scope.isSmallDevice = true;
            } else {
                $scope.isSmallDevice = false;
            }
            if (newValue.w <= 768) {
                $scope.isMobileDevice = true;
            } else {
                $scope.isMobileDevice = false;
            }
        }, true);
        // Apply on resize
        $win.on('resize', function() {
            $scope.$apply();
        });
    }
]);